package cn.yanhu.kuwanapp.welfare

import android.media.MediaPlayer
import android.os.SystemClock
import android.util.Log
import android.widget.Chronometer
import android.widget.Chronometer.OnChronometerTickListener
import cn.woochen.comlib.BaseFragment
import cn.woochen.comlib.util.UserPref
import cn.yanhu.kuwanapp.R
import cn.yanhu.kuwanapp.databinding.FragmentVideoBinding
import cn.yanhu.kuwanapp.utils.constans.Constants
import cn.yanhu.kuwanapp.utils.ext.logcom
import cn.yanhu.kuwanapp.utils.ext.parseState
import com.yilan.sdk.data.user.YLUser
import com.yilan.sdk.player.ylplayer.callback.OnPlayerCallBack
import com.yilan.sdk.ui.configs.LittleVideoConfig
import com.yilan.sdk.ui.configs.YLUIConfig
import com.yilan.sdk.ui.configs.callback.CommentCallback
import com.yilan.sdk.ui.little.YLLittleVideoFragment
import com.yilan.sdk.ylad.YLAdListener
import pl.droidsonroids.gif.GifDrawable
import java.io.IOException
import java.util.*

/**
 *
 * 类描述：好兔视频
 * @author：woochen
 * create at：2021/7/27 10:38 PM
 */
class VideoFragment:BaseFragment<FragmentVideoBinding, WelfareViewModel>() {

    // 记录已播放过的视频
    private val map = HashMap<String, String>()

    private val fragment: YLLittleVideoFragment by lazy {
        YLLittleVideoFragment.newInstance()
    }
    private var gifDrawable :GifDrawable?=null
    private val mediaPlayer by lazy {
        MediaPlayer.create(mContext, R.raw.coins)
    }

    override fun registerNecessaryObserver() {
        super.registerNecessaryObserver()
        //视频金币领取
        mViewModel.videoRewardInfo.observe(this, androidx.lifecycle.Observer {
            parseState(it, {
                logcom("领取奖励成功～～～")
            })
        })
    }
    override fun setContentView(): Int = R.layout.fragment_video

    override fun initData() {
        childFragmentManager.beginTransaction().replace(R.id.short_content, fragment).commitAllowingStateLoss()
        initWidgets()
    }

    private fun initWidgets() {
        try {
            gifDrawable = GifDrawable(resources, R.drawable.video1)
        } catch (e: IOException) {
            e.printStackTrace()
        }
        mBinding.ivFloat.setImageDrawable(gifDrawable)
        gifDrawable!!.stop()
        gifDrawable!!.loopCount = 1
        // 音效
        try {
            mediaPlayer.prepare()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        mBinding.progressBar.setCurrentAngle(360f)
        //设置起始时间为当前时间
        mBinding.chronometer.base = SystemClock.elapsedRealtime()
        //设置显示格式
        mBinding.chronometer.format = "%s"
        onRecordPause()
        mBinding.chronometer.onChronometerTickListener = OnChronometerTickListener { chronometer: Chronometer ->
            Log.d("coin---", ((SystemClock.elapsedRealtime() - chronometer.base) % 20000L).toString())
            if ((SystemClock.elapsedRealtime() - chronometer.base) % 20000 >= 19000) {
                //                ToastUtil.toastShortMessage("领取奖励～～～");
                Log.d("coin---", "领取～～～")
                mViewModel.videoReward("","3","")
                gifDrawable!!.reset()
                mediaPlayer.start()
            }
        }
        //注册评论回调
        YLUIConfig.getInstance().registerCommentCallBack(object : CommentCallback {
            override fun onCommentClick(s: String?) {}
            override fun onCommentShow(s: String?): Boolean {
                return false
            }

            override fun onCommentHide(s: String?) {}
            override fun onCommentSend(s: String?) {}
        })
        //视频配置
        LittleVideoConfig.getInstance().registerPlayerCallBack(object : OnPlayerCallBack {
            /**
             * 开始播放
             * @param videoID 视频id
             * @param taskID  本次播放任务唯一标识
             */
            override fun onStart(pager: String, videoID: String, taskID: String) {
                Log.d("video--", "开始播放$pager---$videoID---$taskID")
                if (map.containsKey(videoID)) {
                    // 播放过的视频,不计时
                    mBinding.progressBar.pauseProgress()
                    onRecordPause()
                } else {
                    mBinding.progressBar.startProgress()
                    onRecordStart()
                }
                //                EventMarkManger.getInstance().markVideo(EventKey.APP_VIDEO_PLAY.getEventName(), videoID, "0")
            }

            /**
             * 暂停播放
             *
             * @param videoID 视频id
             * @param taskID  本次播放任务唯一标识
             */
            override fun onPause(pager: String, videoID: String, taskID: String) {
                Log.d("video--", "暂停播放---$videoID---$taskID")
                mBinding.progressBar.pauseProgress()
                onRecordPause()
            }

            /**
             * 继续播放
             *
             * @param videoID 视频id
             * @param taskID  本次播放任务唯一标识
             */
            override fun onResume(pager: String, videoID: String, taskID: String) {
                Log.d("video--", "继续播放---$videoID---$taskID")
                if (map.containsKey(videoID)) {
                    // 播放过的视频,不计时
                    mBinding.progressBar.pauseProgress()
                    onRecordPause()
                } else {
                    mBinding.progressBar.startProgress()
                    onRecordStart()
                }
            }

            /**
             * 播放完成
             *
             * @param videoID 视频id
             * @param taskID  本次播放任务唯一标识
             */
            override fun onComplete(pager: String, videoID: String, taskID: String) {
                Log.d("video--", "播放完成---$videoID---$taskID")
                if (!map.containsKey(videoID)) map[videoID] = taskID
                mBinding.progressBar.pauseProgress()
                onRecordPause()
            }

            /**
             * 在循环播放模式下，一次播放完成
             *
             * @param videoID 视频id
             * @param taskID  本次播放任务唯一标识
             * @param num     第几次循环播放
             */
            override fun onLoopComplete(pager: String, videoID: String, taskID: String, num: Int) {
                Log.d("video--", "在循环播放模式下，一次播放完成---$videoID---$taskID---$num")
                if (!map.containsKey(videoID)) map[videoID] = taskID
                mBinding.progressBar.pauseProgress()
                onRecordPause()
            }

            /**
             * 视频卡顿，开始缓冲
             *
             * @param videoID 视频id
             * @param taskID  本次播放任务唯一标识
             */
            override fun onStuckStart(pager: String, videoID: String, taskID: String) {
                Log.d("video--", "开始缓冲---$videoID---$taskID")
                mBinding.progressBar.pauseProgress()
                onRecordPause()
            }

            /**
             * 视频卡顿，缓冲完毕，继续播放
             *
             * @param videoID 视频id
             * @param taskID  本次播放任务唯一标识
             */
            override fun onStuckEnd(pager: String, videoID: String, taskID: String) {
                Log.d("video--", "视频卡顿，缓冲完毕，继续播放---$videoID---$taskID")
                if (map.containsKey(videoID)) {
                    // 播放过的视频,不计时
                    mBinding.progressBar.pauseProgress()
                    onRecordPause()
                } else {
                    mBinding.progressBar.startProgress()
                    onRecordStart()
                }
            }

            /**
             * 视频播放错误
             *
             * @param videoID 视频id
             * @param taskID  本次播放任务唯一标识
             */
            override fun onError(pager: String, videoID: String, taskID: String) {
                Log.d("video--", "视频播放错误---$videoID---$taskID")
                mBinding.progressBar.pauseProgress()
                onRecordPause()
            }

            /**
             * 视频停止
             *
             * @param videoID 视频id
             * @param taskID  本次播放任务唯一标识
             */
            override fun onStop(pager: String, videoID: String, taskID: String) {
                Log.d("video--", "视频停止---$videoID---$taskID")
                mBinding.progressBar.pauseProgress()
                onRecordPause()
            }
        })

        // 广告

        // 广告
        YLUIConfig.getInstance().registerAdListener(object : YLAdListener() {
            /**
             * 广告请求成功
             *
             * @param adType 广告类型
             * @param reqId  请求id
             * @param pid    广告位id
             */
            fun onSuccess(adType: String, reqId: String, pid: String) {
                Log.d("ad--", "广告请求成功---$adType---$reqId---$pid")
            }

            /**
             * 广告请求失败
             *
             * @param adType 广告类型
             * @param code   错误码
             * @param msg    错误信息
             * @param pid    广告位id
             */
            fun onError(adType: String, reqId: String, code: Int, msg: String, pid: String) {
                Log.d("ad--", "广告请求失败---$adType---$reqId---$code---$msg---$pid")
            }

            /**
             * 广告渲染失败
             *
             * @param adType 广告类型
             * @param code   错误码
             * @param msg    错误信息
             * @param pid    广告位id
             */
            fun onRenderError(adType: String, code: Int, msg: String, pid: String) {
                Log.d("ad--", "广告渲染失败---$adType---$msg---$pid")
            }

            /**
             * 广告展现
             *
             * @param adType 广告类型
             * @param reqId  请求id
             * @param pid    广告位id
             */
            fun onShow(adType: String, reqId: String, pid: String) {
                Log.d("ad--", "广告展现---$adType---$reqId---$pid")
            }

            /**
             * @param adType 广告类型
             * @param reqId  请求id
             * @param pid    广告位id
             */
            fun onClick(adType: String, reqId: String, pid: String) {
                Log.d("ad--", "广告类型---$adType---$reqId---$pid")
            }

            /**
             * 跳过回调，如开屏广告
             *
             * @param adType 广告类型
             * @param reqId  请求id
             * @param pid    广告位id
             */
            fun onSkip(adType: String, reqId: String, pid: String) {
                Log.d("ad--", "跳过回调，如开屏广告---$adType---$reqId---$pid")
            }

            /**
             * 广告结束，如开屏广告
             *
             * @param adType 广告类型
             * @param reqId  请求id
             * @param pid    广告位id
             */
            fun onTimeOver(adType: String, reqId: String, pid: String) {
                Log.d("ad--", "广告结束，如开屏广告---$adType---$reqId---$pid")
            }

            /**
             * 广告被关闭
             *
             * @param adType 广告类型
             * @param reqId  请求id
             * @param pid    广告位id
             */
            fun onClose(adType: String, reqId: String, pid: String) {
                Log.d("ad--", "广告被关闭---$adType---$reqId---$pid")
            }

            /**
             * 没有广告
             *
             * @param adType 广告类型
             * @param reqId  请求id
             * @param pid    广告位id
             */
            fun onAdEmpty(adType: String, reqId: String, pid: String) {
                Log.d("ad--", "没有广告---$adType---$reqId---$pid")
            }

            fun onVideoStart(s: String, s1: String, s2: String) {
                Log.d("ad--", "onVideoStart---$s---$s1---$s2")
                if (map.containsKey(s1)) {
                    Log.d("ad--", "这个广告已经看过～～")
                    // 播放过的视频,不计时
                    mBinding.progressBar.pauseProgress()
                    onRecordPause()
                } else {
                    mBinding.progressBar.startProgress()
                    onRecordStart()
                }
                //                EventMarkManger.getInstance().markVideo(EventKey.APP_VIDEO_PLAY.getEventName(), s1, "1")
            }

            fun onVideoPause(s: String, s1: String, s2: String) {
                Log.d("ad--", "onVideoPause---$s---$s1---$s2")
                mBinding.progressBar.pauseProgress()
                onRecordPause()
            }

            fun onVideoResume(s: String, s1: String, s2: String) {
                Log.d("ad--", "onVideoResume---$s---$s1---$s2")
                if (map.containsKey(s1)) {
                    // 播放过的视频,不计时
                    mBinding.progressBar.pauseProgress()
                    onRecordPause()
                } else {
                    mBinding.progressBar.startProgress()
                    onRecordStart()
                }
            }

            fun onVideoComplete(s: String, s1: String, s2: String) {
                Log.d("ad--", "onVideoComplete---$s---$s1---$s2")
                if (!map.containsKey(s1)) map[s1] = s2
                mBinding.progressBar.pauseProgress()
                onRecordPause()
            }

            fun onVideoError(s: String, s1: String, s2: String) {
                Log.d("ad--", "onVideoError---$s---$s1---$s2")
                mBinding.progressBar.pauseProgress()
                onRecordPause()
            }
        })
    }

    private var pauseTime: Long = 0
    private var isPause = false

    fun onRecordStart() {
        mBinding.chronometer.base = mBinding.chronometer.base + (SystemClock.elapsedRealtime() - pauseTime)
        mBinding.chronometer.start()
        isPause = false
    }
   private fun onRecordPause() {
        if (!isPause) {
            mBinding.chronometer.stop()
            pauseTime = SystemClock.elapsedRealtime()
            Log.d("video--", "pauseTime---$pauseTime")
        }
        isPause = true
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        if (isVisibleToUser) videoLogin()
        super.setUserVisibleHint(isVisibleToUser)
        fragment.userVisibleHint = isVisibleToUser
    }
    private var mUserId by UserPref(Constants.USER_ID, "")
    private var mNickname by UserPref(Constants.USER_NICKNAME, "")
    private var mHeadUrl by UserPref(Constants.USER_HEAD_URL, "")
    private var mToken by UserPref(Constants.USER_TOKEN, "")

    private fun videoLogin() {
        if (mToken.isNotBlank()) {
            //            ToastUtil.toastShortMessage("登陆！！！");
            YLUser.getInstance().addListener { b: Boolean -> Log.d("LoginStateChange--", "LoginStateChange---$b") }
            YLUser.getInstance().login(mNickname, mHeadUrl, "", mUserId)
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        fragment.onHiddenChanged(hidden)
    }

    override fun onPause() {
        super.onPause()
        fragment.onPause()
    }

    override fun onResume() {
        super.onResume()
        fragment.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        // 销毁视频回调
        LittleVideoConfig.getInstance().unRegisterPlayerCallback()
        YLUIConfig.getInstance().unRegisterAdListener()
        YLUIConfig.getInstance().unregisterCommentCallBack()
        mediaPlayer.stop()
        mediaPlayer.release()
        fragment.onDestroy()
    }


    override fun requestData() {

    }

    companion object{
        fun newInstance() = VideoFragment()
    }
}